<?php
declare (strict_types = 1);

namespace app\middleware;

use app\exception\TokenException;
use think\facade\Cache;
use xiaodi\JWTAuth\Facade\Jwt;


class LoginMiddleware
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure $next
     * @return Response
     * @throws TokenException
     */
    public function handle($request, \Closure $next)
    {
        $path = $request->baseUrl();

        if($request->baseUrl() != '/account/login' && !preg_match('/themeFile\/design/',$path)){
            try{
                // 验证token
                $authorization = $request->header('authorization');
                if(empty($authorization)){
                    throw new TokenException("请先登录");
                }
                $request->token = substr($authorization,7);
                $request->admin = $this->getUserSimpleInfo($request,$request->token);
            }catch(\Exception $e){
                throw new TokenException($e->getMessage());
            }
        }
        return $next($request);
    }

    private function getUserSimpleInfo($request,$token)
    {
        $jwtConfig = config("jwt")['stores']['token'];
        $jwtObject = \EasySwoole\Jwt\Jwt::getInstance()->setSecretKey($jwtConfig['signer_key'])->decode($token);
        $status = $jwtObject->getStatus();
        switch ($status)
        {
            case  1:
                if($jwtObject->getSub()!="admin"){
                    throw new TokenException('没有权限');
                }
                break;
            case  -1:
                throw new TokenException('请先登录');
            case  -2:
                throw new TokenException('登录已过期,请重新登录');
        }
        $request->jti = $jwtObject->getJti();
        $request->exp = $jwtObject->getExp();
        //判断在不在黑名单里
        $blackUserToken = Cache::get("black_{$request->jti}");
        if(!empty($blackUserToken)){
            throw new TokenException('信息已过期,请重新登录');
        }
        return $jwtObject->getData();
    }
}
